package com.lemon.cloud.springdoc;

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Profile;

import java.util.Optional;
/**
 * @author HuangDS
 */
@Configuration
@Profile(value = {"dev","test"})
@Import(SpringDocProperties.class)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
public class SpringFluxDocConfiguration {

    @Value(value = "${server.port:6061}")
    private int port;

    @Autowired
    private SpringDocProperties springDocProperties;

    @Bean
    public OpenAPI openAPI() {
        SpringDocProperties.ApiInfo apiInfo = Optional.ofNullable(springDocProperties.getApiInfo()).orElse(new SpringDocProperties.ApiInfo());
        final String loginToken = "Bearer";
        return new OpenAPI().info(new Info().title(apiInfo.getTitle())
                .description(apiInfo.getDescription())
                .version(apiInfo.getVersion()))
                .externalDocs(new ExternalDocumentation()
                        .url("http://127.0.0.1:" + port))
                .components(new Components().addSecuritySchemes(loginToken, new SecurityScheme()
                        .type(SecurityScheme.Type.HTTP).scheme(loginToken).bearerFormat("JWT")
                        .in(SecurityScheme.In.HEADER)
                        .name(loginToken)))
                .addSecurityItem(new SecurityRequirement().addList(loginToken));
    }

    @Bean
    public GroupedOpenApi service2Api() {
        String[] paths = {"/_default/**"};
        return GroupedOpenApi.builder().group("_default")
                .pathsToMatch(paths)
                .build();
    }
}
